package Q383;

import java.util.Arrays;

/**
 * 每日一题
 *
 * @author 23737
 * @time 2021.12.4
 */
public class Test {
    public static void main(String[] args) {
        System.out.println(new Solution().canConstruct("aa", "ab"));
    }
}

/**
 * api大法
 * 不能连续判断，过不了全部样例
 */
class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        char[] chars = ransomNote.toCharArray();
        char[] chars1 = magazine.toCharArray();
        Arrays.sort(chars);
        Arrays.sort(chars1);
        StringBuilder stringBuilder = new StringBuilder();
        StringBuilder stringBuilder2 = new StringBuilder();
        for (char aChar : chars) {
            stringBuilder.append(aChar);
        }
        for (char c : chars1) {
            stringBuilder2.append(c);
        }
        String s = stringBuilder.toString();
        String s1 = stringBuilder2.toString();
        return s1.contains(s);
//        return magazine.contains(ransomNote);
    }
}

/**
 * 使用字符数组统计个数
 */
class Solution2 {
    public boolean canConstruct(String ransomNote, String magazine) {
        char[] charsRan = ransomNote.toCharArray();
        char[] charsMa = magazine.toCharArray();
        int[] res = new int[26];
        //统计magazine中字符出现的次数
        for (char c : charsMa) {
            res[c - 'a']++;
        }

        //开始在ransomNote遍历减次数
        for (char c : charsRan) {
            if(res[c-'a'] > 0){
                res[c-'a']--;
            }else {
                return false;
            }
        }
        //能出循环 charsRan 里边的元素都被减干净了
        return true;
    }
}
